package com.water.wfo.user.business.service.impl;

import com.water.wfo.component.api.domain.WfoCookie;
import com.water.wfo.component.api.exception.BusinessException;
import com.water.wfo.component.api.filter.RequestFilter;
import com.water.wfo.component.api.interceptor.AuthenticationInterceptor;
import com.water.wfo.component.util.StringUtil;
import com.water.wfo.sys.pojo.dto.LoginUserInfoDto;
import com.water.wfo.sys.pojo.entity.MenuEntity;
import com.water.wfo.sys.pojo.entity.RoleMenuRelEntity;
import com.water.wfo.sys.pojo.entity.UserEntity;
import com.water.wfo.sys.pojo.entity.UserExtEntity;
import com.water.wfo.user.ability.MenuAbility;
import com.water.wfo.user.ability.RoleMenuRelAbility;
import com.water.wfo.user.ability.UserAbility;
import com.water.wfo.user.ability.UserExtAbility;
import com.water.wfo.user.business.service.ILoginOutService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * packageName com.water.wfo.user.business.service.impl
 *
 * @author
 * @className LoginOutServiceImpl(处以class为网)
 * @date 2024/8/20
 * @description T0D0
 */
@Component
public class LoginOutServiceImpl implements ILoginOutService {
    @Autowired
    private UserAbility userAbility;
    @Autowired
    private MenuAbility menuAbility;
    @Autowired
    private UserExtAbility userExtAbility;
    @Autowired
    private RoleMenuRelAbility roleMenuRelAbility;
    @Override
    public LoginUserInfoDto login(String loginId, String password) throws Exception {
        UserEntity userEntity = userAbility.selectUserById(loginId);
        if(null != userEntity){
            if(StringUtil.equals(password,userEntity.getPassword())){
                WfoCookie.saveCookie();
                Cookie cookie = AuthenticationInterceptor.getCookie();
                if (cookie != null) {
                    String paramToken = cookie.getValue();
                    paramToken = StringUtil.replace(paramToken, "-", "+");
                    paramToken = StringUtil.replace(paramToken, "_", "/");
                    String token = new String(Base64.decodeBase64(paramToken), "UTF-8");
                    String[] keys = token.split(",");
                    String userId = keys[1];
                    Cookie casCookie = new Cookie("CAS_TGC", userId);
                    casCookie.setPath("/");
                    casCookie.setMaxAge(-1);
                    HttpServletResponse response = (HttpServletResponse) RequestFilter.getResponseMap().get();
                    response.addCookie(casCookie);
                }
                LoginUserInfoDto loginUserInfoDto = new LoginUserInfoDto();
                /*if(null != userEntity.getIsAdmin() && userEntity.getIsAdmin().intValue() == NumberConstans.NUMBER_1){
                    List<MenuEntity> menuEntities = menuAbility.queryAllMenuEntity();
                    List<MenuEntity> allMenus = new ArrayList<MenuEntity>();
                    this.sort(this.getAllAvailableMenu(menuEntities),allMenus,null, 0);
                    loginUserInfoDto.setMenus(allMenus);
                }else {
                    List<MenuEntity> menuEntities = this.queryMenuEntityByUserId(userEntity.getId());
                    List<MenuEntity> allMenus = new ArrayList<MenuEntity>();
                    this.sort(this.getAllAvailableMenu(menuEntities),allMenus,null, 0);
                    loginUserInfoDto.setMenus(allMenus);
                }
                userEntity.setPassword(null);
                loginUserInfoDto.setLoginId(userEntity.getLoginId());
                loginUserInfoDto.setLoginName(userEntity.getLoginName());
                loginUserInfoDto.setUserEntity(userEntity);
                loginUserInfoDto.setToken(StringUtil.createToken());
                LoginUserContext.setCurrentUser(loginUserInfoDto);*/
                return loginUserInfoDto;
            }else {
                throw new BusinessException("密码不正确！");
            }
        }else {
            throw new BusinessException("用户不存在！");
        }
    }

    @Override
    public void loginOut() {
       // LoginUserContext.remove();
    }

    /**
     * @Author Administrator
     * @Description 根据用户ID 查询用户信息
     * * @param userId
     * @Return java.util.List<com.water.wfo.sys.pojo.entity.MenuEntity>
     * @Date 2024/8/21 17:26
     *
     */
    private List<MenuEntity> queryMenuEntityByUserId(Long userId){
        UserExtEntity extEntity = new UserExtEntity();
        extEntity.setUserId(userId);
        List<UserExtEntity> userExtEntities = userExtAbility.queryUserExtEntityBy(extEntity);
        UserExtEntity userExtEntity = null;
        if(CollectionUtils.isNotEmpty(userExtEntities)){
            userExtEntity = userExtEntities.get(0);
            RoleMenuRelEntity roleMenuRelEntity = new RoleMenuRelEntity();
            roleMenuRelEntity.setRoleId(userExtEntity.getRoleId());
            List<RoleMenuRelEntity> roleMenuRelEntities = roleMenuRelAbility.queryRoleMenuRelEntityBy(roleMenuRelEntity);
            List<Long> ids = new ArrayList<>();
            for (RoleMenuRelEntity relEntity : roleMenuRelEntities){
                if(null != relEntity){
                    ids.add(relEntity.getMenuId());
                }
            }
           return menuAbility.queryMenuEntityByIds(ids);
        }
        return Collections.EMPTY_LIST;
    }

    /**
     *  去除没有可用页面的模块
     *
     * @return
     */
    public List<MenuEntity> getAllAvailableMenu(List<MenuEntity> menus) {
        MenuEntity menu=new MenuEntity();
        Boolean bool=true;
        for (int i = 0; i < menus.size(); i++) {
            menu=menus.get(i);
            if(menu.getType()==0){
                for (int j = 0; j < menus.size(); j++) {
                    if(menu.getId()==menus.get(j).getParentId()){
                        bool=false;
                        break;
                    }
                }
                if(bool){
                    menus.remove(i);
                }
                bool=true;
            }
        }
        return menus;
    }

    public void sort(List<MenuEntity> menus, List<MenuEntity> newMenus, MenuEntity menu,
                     int cj) {
        if (menu == null) {
            for (int j = 0; j < menus.size(); j++) {
                MenuEntity mu = menus.get(j);
                if (mu.getId() == 1) {
                    mu.setMenuLevel(cj);
                    newMenus.add(mu);
                    sort(menus, newMenus, mu, cj);
                    break;
                }
            }
            return;
        }
        if (newMenus.size() == 0) {
            newMenus.add(menu);
        }
        cj++;
        for (MenuEntity mu : menus) {
            if (menu.getId() == mu.getParentId()) {
                mu.setMenuLevel(cj);
                newMenus.add(mu);
                sort(menus, newMenus, mu, cj);
            }
        }
    }
}
